#include"TCP.h"
#include<sys/epoll.h>

int main(int argc,char **argv)
{
    int sockfd;
    int cfd;
    int epfd;

    socklen_t c_size;
    
    struct epoll_event event;
        
    struct epoll_event events[1024];
    struct sockaddr_in *c_addr;

    char msg[1024];

    sockfd=TCP_server_create();
    epfd=epoll_create(2000);
    event.events=EPOLLIN;
    event.data.fd = sockfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
    while (1)
    {
        int rnum =  epoll_wait(epfd,events,1024,-1);
        for(int i=0;i<rnum;i++)
        {
            if(events[i].events==EPOLLIN)
            {
                if(events[i].data.fd == sockfd)
                {
                    c_size=sizeof(struct sockaddr_in);
                    cfd=accept(sockfd,(struct sockaddr*)&c_addr,&c_size);
                    if(cfd<0)
                    {
                        if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
                        {
                            perror("accept error\n");
                            exit(1);
                        }
                        continue;
                    }
                    printf("连接\n");
                    event.events=EPOLLIN;
                    event.data.fd=cfd;
                    epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&event);
                    if(--rnum<=0)
                    {
                        break;
                    }
                }
                else
                {
                    int fd=events[i].data.fd;
                    memset(msg,0,1024);
                    int r_n = read(fd,msg,sizeof(msg));
                    if(r_n<=0)
                    {
                        close(fd);
                        epoll_ctl(epfd,EPOLL_CTL_DEL,fd,&event);
                    }
                    write(fd,msg,strlen(msg));
                    if(--rnum<=0)
                    {
                        break;
                    }
                }
            }
            
        }
    }
    
    return 0;
}